package com.cll.prototype.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cll.prototype.common.dto.AjaxResult;
import com.cll.prototype.common.user.entity.LoginToken;
import com.cll.prototype.common.user.mapper.LoginTokenMapper;
import com.cll.prototype.common.user.service.ILoginTokenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cll.prototype.common.util.UUIDUtils;
import com.cll.prototype.common.util.ValidateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户登录成功之后的令牌（token）表 服务实现类
 * </p>
 *
 * @author CLL
 * @since 2020-10-26
 */
@Service
public class LoginTokenServiceImpl extends ServiceImpl<LoginTokenMapper, LoginToken> implements ILoginTokenService {

    @Override
    public AjaxResult generateLoginToken(String email) {
        if (StringUtils.isBlank(email)) {
            return AjaxResult.error(42, "参数不合法");
        }
        if (!ValidateUtils.checkEmailAddress(email)) {
            return AjaxResult.error(46, "邮箱地址不合法");
        }
        String token = UUIDUtils.getInstance();
        LoginToken loginToken = new LoginToken();
        loginToken.setEmail(email);
        loginToken.setToken(token);
        loginToken.setGmtCreate(LocalDateTime.now());
        boolean save = save(loginToken);
        return save ? AjaxResult.success(20, "登录成功", token) : AjaxResult.error("系统错误");
    }

    @Override
    public AjaxResult getEmailByToken(String token) {
        LoginToken loginToken = getOne(Wrappers.<LoginToken>query().eq("token", token));
        if (null == loginToken) {
            return AjaxResult.error(43, "token不合法");
        }
        return AjaxResult.success(20, "获取成功", loginToken.getEmail());
    }
}
